package org.xiyu.yee.pjwto.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import org.xiyu.yee.pjwto.Constants;
import org.xiyu.yee.pjwto.trading.PiglinTrade;
import org.xiyu.yee.pjwto.trading.PiglinTradeManager;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 猪灵交易配置管理器
 */
public class PiglinTradeConfig {
    
    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
    private static final String CONFIG_FILE_NAME = "piglin_trades.json";
    
    /**
     * 加载配置文件
     */
    public static void loadConfig(File configDir) {
        Path configPath = Paths.get(configDir.getAbsolutePath(), CONFIG_FILE_NAME);
        
        if (!Files.exists(configPath)) {
            createDefaultConfig(configPath);
            return;
        }
        
        try (FileReader reader = new FileReader(configPath.toFile())) {
            JsonObject json = GSON.fromJson(reader, JsonObject.class);
            loadCustomTrades(json);
            Constants.LOG.info("Loaded piglin trade config from {}", configPath);
        } catch (IOException e) {
            Constants.LOG.error("Failed to load piglin trade config", e);
            createDefaultConfig(configPath);
        }
    }
    
    /**
     * 创建默认配置文件
     */
    private static void createDefaultConfig(Path configPath) {
        JsonObject config = new JsonObject();
        config.addProperty("_comment", "Piglin trading configuration. Define custom trades here.");
        
        JsonArray customTrades = new JsonArray();
        
        // 示例交易：钻石
        JsonObject diamondTrade = new JsonObject();
        diamondTrade.addProperty("result_item", "minecraft:diamond");
        diamondTrade.addProperty("result_count", 1);
        diamondTrade.addProperty("cost_a_item", "minecraft:gold_ingot");
        diamondTrade.addProperty("cost_a_count", 10);
        diamondTrade.addProperty("cost_b_item", "");
        diamondTrade.addProperty("cost_b_count", 0);
        diamondTrade.addProperty("max_uses", 5);
        diamondTrade.addProperty("experience", 10);
        customTrades.add(diamondTrade);
        
        // 示例交易：下界合金碎片
        JsonObject netheriteTrade = new JsonObject();
        netheriteTrade.addProperty("result_item", "minecraft:netherite_scrap");
        netheriteTrade.addProperty("result_count", 1);
        netheriteTrade.addProperty("cost_a_item", "minecraft:gold_ingot");
        netheriteTrade.addProperty("cost_a_count", 20);
        netheriteTrade.addProperty("cost_b_item", "");
        netheriteTrade.addProperty("cost_b_count", 0);
        netheriteTrade.addProperty("max_uses", 2);
        netheriteTrade.addProperty("experience", 20);
        customTrades.add(netheriteTrade);
        
        // 示例交易：需要两种物品
        JsonObject complexTrade = new JsonObject();
        complexTrade.addProperty("result_item", "minecraft:enchanted_golden_apple");
        complexTrade.addProperty("result_count", 1);
        complexTrade.addProperty("cost_a_item", "minecraft:gold_ingot");
        complexTrade.addProperty("cost_a_count", 32);
        complexTrade.addProperty("cost_b_item", "minecraft:apple");
        complexTrade.addProperty("cost_b_count", 1);
        complexTrade.addProperty("max_uses", 1);
        complexTrade.addProperty("experience", 50);
        customTrades.add(complexTrade);
        
        config.add("custom_trades", customTrades);
        
        try {
            Files.createDirectories(configPath.getParent());
            try (FileWriter writer = new FileWriter(configPath.toFile())) {
                GSON.toJson(config, writer);
            }
            Constants.LOG.info("Created default piglin trade config at {}", configPath);
        } catch (IOException e) {
            Constants.LOG.error("Failed to create default config", e);
        }
    }
    
    /**
     * 从JSON加载自定义交易
     */
    private static void loadCustomTrades(JsonObject config) {
        if (!config.has("custom_trades")) {
            return;
        }
        
        JsonArray trades = config.getAsJsonArray("custom_trades");
        for (int i = 0; i < trades.size(); i++) {
            JsonObject tradeJson = trades.get(i).getAsJsonObject();
            
            try {
                PiglinTrade trade = parseTradeFromJson(tradeJson);
                Item resultItem = getItemFromString(tradeJson.get("result_item").getAsString());
                
                if (trade != null && resultItem != null) {
                    PiglinTradeManager.addCustomTrade(resultItem, trade);
                    Constants.LOG.debug("Loaded custom trade for {}", 
                        BuiltInRegistries.ITEM.getKey(resultItem));
                }
            } catch (Exception e) {
                Constants.LOG.error("Failed to parse trade at index {}", i, e);
            }
        }
    }
    
    /**
     * 从JSON解析交易
     */
    private static PiglinTrade parseTradeFromJson(JsonObject json) {
        String resultItemStr = json.get("result_item").getAsString();
        int resultCount = json.get("result_count").getAsInt();
        
        String costAItemStr = json.get("cost_a_item").getAsString();
        int costACount = json.get("cost_a_count").getAsInt();
        
        String costBItemStr = json.get("cost_b_item").getAsString();
        int costBCount = json.get("cost_b_count").getAsInt();
        
        int maxUses = json.get("max_uses").getAsInt();
        int experience = json.get("experience").getAsInt();
        
        Item resultItem = getItemFromString(resultItemStr);
        Item costAItem = getItemFromString(costAItemStr);
        Item costBItem = costBItemStr.isEmpty() ? null : getItemFromString(costBItemStr);
        
        if (resultItem == null || costAItem == null) {
            return null;
        }
        
        ItemStack result = new ItemStack(resultItem, resultCount);
        ItemStack costA = new ItemStack(costAItem, costACount);
        ItemStack costB = costBItem != null ? new ItemStack(costBItem, costBCount) : ItemStack.EMPTY;
        
        return new PiglinTrade(costA, costB, result, maxUses, experience);
    }
    
    /**
     * 从字符串获取物品
     */
    private static Item getItemFromString(String itemStr) {
        if (itemStr == null || itemStr.isEmpty()) {
            return null;
        }
        
        try {
            // 解析物品ID字符串（格式：namespace:path）
            String namespace, path;
            if (itemStr.contains(":")) {
                String[] parts = itemStr.split(":", 2);
                namespace = parts[0];
                path = parts[1];
            } else {
                // 如果没有命名空间，默认使用minecraft
                namespace = "minecraft";
                path = itemStr;
            }
            
            ResourceLocation location = ResourceLocation.tryBuild(namespace, path);
            if (location == null) {
                Constants.LOG.error("Invalid item ID format: {}", itemStr);
                return null;
            }
            
            return BuiltInRegistries.ITEM.get(location);
        } catch (Exception e) {
            Constants.LOG.error("Invalid item ID: {}", itemStr, e);
            return null;
        }
    }
}
